package com.ziven.common.widget.index;

import android.view.View;

import androidx.annotation.NonNull;
import androidx.collection.LongSparseArray;
import androidx.recyclerview.widget.RecyclerView;

import com.ziven.easygo.util.Carry;
import com.ziven.easygo.util.Nulls;

import java.lang.ref.WeakReference;
import java.util.Objects;

/**
 * @author Ziven
 */
final class ViewCache implements RecyclerView.OnChildAttachStateChangeListener, RecyclerView.RecyclerListener {

    private final LongSparseArray<WeakReference<View>> viewCache;

    public ViewCache() {
        viewCache = new LongSparseArray<>();
    }

    private void put(@NonNull View view) {
        int key = Objects.hashCode(view);
        WeakReference<View> weak = viewCache.get(key);
        if (weak == null || weak.get() == null) {
            viewCache.put(key, new WeakReference<>(view));
        }
    }

    private void remove(@NonNull View view) {
        viewCache.remove(Objects.hashCode(view));
    }

    private boolean has(@NonNull View view) {
        return viewCache.containsKey(Objects.hashCode(view));
    }

    public void forEach(@NonNull Carry<View> carry) {
        for(int i=0; i<viewCache.size(); i++) {
            Nulls.of(viewCache.valueAt(i).get()).doNotNull(carry::carry);
        }
    }

    @Override
    public void onChildViewAttachedToWindow(@NonNull View view) {
        put(view);
    }

    @Override
    public void onChildViewDetachedFromWindow(@NonNull View view) {

    }

    @Override
    public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
        remove(holder.itemView);
    }
}
